import { supabase } from "@/ultils/supabase.js";

export async function getStudentListWithLimit(
  teacherId,
  currentPage,
  pageSize
) {
  const { data: student, error } = await supabase
    .from("student")
    .select("*")
    .eq("teacher_id", teacherId)
    .range((currentPage - 1) * pageSize, currentPage * pageSize - 1);

  if (error) {
    console.log(error.message);
    return;
  }

  return student;
}

export async function countStudent(teacherId) {
  const { count, error } = await supabase
    .from("student")
    .select("*", { count: "exact", head: true })
    .eq("teacher_id", teacherId);

  if (error) {
    console.log(error.message);
    return;
  }
  return count;
}

export async function getStudentList(teacherId) {
  const { data: student, error } = await supabase
    .from("student")
    .select("*")
    .eq("teacher_id", teacherId);

  if (error) {
    console.log(error.message);
    return;
  }

  return student;
}

// 2. 定义通过ID查询数据的函数
export async function getStuentById(column, id) {
  // 使用select查询，加上eq筛选条件
  const { data: student, error } = await supabase
    .from("student")
    .select("*")
    .eq(column, id);

  if (error) {
    console.log(error.message);
    return; // 返回null表示查询失败
  }

  return student; // 返回查询到的数据
}

export async function createStudent(newStudent) {
  const { data, error } = await supabase
    .from("student")
    .insert([newStudent])
    .select();
  if (error) {
    console.log(error.message);
    return;
  }
  return data;
}

export async function updateStudent(studentId, newStudent) {
  const { data, error } = await supabase
    .from("student")
    .update(newStudent)
    .eq("student_id", studentId)
    .select();
  if (error) {
    console.log(error.message);
    return;
  }
  return data;
}

export async function getStuentByStuentId(id) {
  // 使用select查询，加上eq筛选条件
  const { data: student, error } = await supabase
    .from("student")
    .select("*")
    .eq("student_id", id);

  if (error) {
    console.log(error.message);
    return; // 返回null表示查询失败
  }

  return student; // 返回查询到的数据
}
